package com.auto.survey.activity.config.dao

import android.util.Log
import com.auto.survey.activity.config.entity.ConfigBean
import com.auto.survey.activity.config.entity.ConfigWithPoints
import com.auto.survey.activity.config.entity.PointConfig
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull

class ConfigRepository(private val configDao: ConfigDao) {
    companion object {
        private val TAG:String = ConfigRepository::class.java.simpleName
    }
    // 更新配置及其关联点位（封装 Dao 中的组合操作）
    suspend fun updateSurveyConfig(config: ConfigBean, newPoints: List<PointConfig>):Int {
        return  configDao.updateConfigWithPoints(config, newPoints)
    }

    suspend fun insertSurveyConfig(config: ConfigBean, newPoints: List<PointConfig>):Int{
        return configDao.insertConfigWithPoints(config, newPoints)
    }

    suspend fun getAllConfigsWithPoints(): List<ConfigWithPoints>? {
        val result = getConfigsWithOrderedPoints().filterEmptyLists().firstOrNull { it != null && it.isNotEmpty() }
        Log.i("ConfigRepository", "getAllConfigsWithPoints JSON = ${Gson().toJson(result)}")
        return result
    }

    private fun getConfigsWithOrderedPoints(): Flow<List<ConfigWithPoints>> {
        return configDao.getDistinctConfigs().map { configs ->
                configs.map { config ->
                    // 同步获取有序点位（IO 线程）
                    val points = configDao.getOrderedPointsForConfig(config.id)
                    ConfigWithPoints(config, points)
                }
            } .flowOn(Dispatchers.IO)
    }


    /**
     * 判断 Flow 中的每个 List<ConfigWithPoints> 是否为空（null 或 empty）。
     * 返回一个新的 Flow，其元素为布尔值，表示对应列表是否为空。
     */
    private  fun Flow<List<ConfigWithPoints>?>.filterEmptyLists(): Flow<List<ConfigWithPoints>> = mapNotNull { it?.takeIf { list -> list.isNotEmpty() } }

    suspend fun deleteAll(){
        configDao.deleteAllPoint()
        configDao.deleteAllConfig()
    }

    suspend fun setConfigsWithPoints(callback: ConfigDbCallback?, bean: ConfigWithPoints) {
        try {
            // 检查当前配置是否存在（根据 ID）
            val configExists = configDao.getConfigById(bean.config.id) != null

            if (configExists) {
                // 配置已存在，执行更新
                val result = updateSurveyConfig(bean.config, bean.points)
                callback?.call(result, "更新配置数据成功")
            } else {
                // 配置不存在，执行插入
                val result = insertSurveyConfig(bean.config, bean.points)
                callback?.call(result, "添加配置数据成功")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(TAG, "数据库操作失败==> exception: ${e.message}")
            callback?.call(-1000, "exception: ${e.message}")
        }
    }

}